<?php

namespace Admin\Controller;

use Common\Controller\BaseController;

/**
 * 地块管理
 */
class BlockController extends BaseController {

    /**
     * 地块列表
     */
    public function blockList() {
        $pageSize = I('post.pageSize', C('PAGE_SIZE'));
        $pageCurrent = I('post.pageCurrent', 1);
        $orderField = I('post.orderField', 'id');
        $orderDirection = I('post.orderDirection', 'DESC');

        $sn = I('post.sn', '');
        $base_id = I('post.base_id', 0);

        //参数数组
        $params = array();
        //构造WHERE条件
        $where = '1=1 ';
        if (!empty($sn)) {
            $params['sn'] = $sn;
            $where .= "AND bl.sn='{$sn}' ";
        }
        if (!empty($base_id)) {
            $params['base_id'] = $base_id;
            $where .= "AND base_id={$base_id} ";
        }

        $block = M('Block');
        //数据总数
        $total = $block->alias('bl')
                ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                ->where($where)
                ->count();

        //数据列表
        $list = $block->field('bl.*,ba.name AS base_name')
                ->alias('bl')
                ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                ->where($where)
                ->order("{$orderField} {$orderDirection}")
                ->page("{$pageCurrent},{$pageSize}")
                ->select();

        if (!empty($list)) {
            //获取苗木分类种类信息
            $treeTypeRet = M('Tree')->group('type_id')->getField('type_id', true);
            $treeTypeIds = implode(',', $treeTypeRet);
            $treeTypeRet = M('TreeType')->field('tt.id,tt.name AS small_name,tt2.name AS large_name')
                    ->alias('tt')
                    ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                    ->where("FIND_IN_SET(tt.id,'{$treeTypeIds}')")
                    ->select();
            $treeTypeInfo = array();
            if (!empty($treeTypeRet)) {
                $tmp = array();
                foreach ($treeTypeRet as $item) {
                    $tmp[$item['id']] = $item['large_name'] . '/' . $item['small_name'];
                }
                $treeTypeInfo = $tmp;
            }


            foreach ($list as &$item) {
                $countInfoArr = array();
                $countInfoRet = M('Tree')->field('type_id,status,COUNT(*) AS num')->where("block_id={$item['id']}")->group('type_id,status')->select();
                if (!empty($countInfoRet)) {
                    foreach ($countInfoRet as $countInfo) {
                        if (!array_key_exists($countInfo['type_id'], $countInfoArr)) {
                            $countInfoArr[$countInfo['type_id']] = $treeTypeInfo[$countInfo['type_id']] . ': ';
                        }

                        if ($countInfo['status'] == 1) {
                            $countInfoArr[$countInfo['type_id']] .= "存圃: {$countInfo['num']}棵 ";
                        } else if ($countInfo['status'] == 2) {
                            $countInfoArr[$countInfo['type_id']] .= "出圃: {$countInfo['num']}棵 ";
                        } else if ($countInfo['status'] == 3) {
                            $countInfoArr[$countInfo['type_id']] .= "死亡: {$countInfo['num']}棵 ";
                        }
                    }
                }
                $item['countInfo'] = implode('<br />', $countInfoArr);
            }
            unset($item);
        }
        
        //获取基地信息
        $base = M('Base')->field('id,name')->where('status=1')->select();

        $this->assign('pageSize', $pageSize);
        $this->assign('pageCurrent', $pageCurrent);
        $this->assign('orderField', $orderField);
        $this->assign('orderDirection', $orderDirection);
        $this->assign('total', $total);
        $this->assign('list', $list);
        $this->assign('params', $params);
        $this->assign('base', $base);
        $this->display();
    }

    /**
     * 添加地块
     */
    public function addBlock() {
        if (IS_POST) {
            $base_id = I('post.base_id', 0);
            $sn = I('post.sn', '');
            $area = I('post.area', 0);
            $block = M('Block');

            if (empty($base_id)) {
                ajaxReturn('请选择所属基地', 300);
            }
            if (empty($sn)) {
                ajaxReturn('地块编号不能为空', 300);
            }
            $existSn = $block->where("sn='{$sn}' AND base_id={$base_id}")->count();
            if ($existSn) {
                ajaxReturn('该地块编号已存在', 300);
            }
            if (empty($area)) {
                ajaxReturn('地块面积不能为空', 300);
            }
            if (floatval($area) < 0) {
                ajaxReturn('地块面积不能小于零', 300);
            }

            $data = $block->create();

            if ($data) {
                $data['add_time'] = time();
                $data['upd_time'] = time();

                $ret = $block->add($data);

                if ($ret) {
                    ajaxReturn('添加地块成功', 200, '', '', '', 'Admin/Block/blockList');
                } else {
                    ajaxReturn('添加地块失败', 300);
                }
            } else {
                ajaxReturn('创建数据对象失败', 300);
            }
        } else {
            //获取所有基地
            $bases = M('Base')->field('id,name')->where('status=1')->select();

            $this->assign('bases', $bases);
            $this->display();
        }
    }

    /**
     * 修改地块
     */
    public function updBlock() {
        if (IS_POST) {
            $blockId = I('post.blockId', 0);
            $base_id = I('post.base_id', 0);
            $sn = I('post.sn', '');
            $area = I('post.area', 0);
            $block = M('Block');

            if (empty($blockId)) {
                ajaxReturn('地块ID不能为空', 300);
            }
            $blockInfo = M('Block')->where("id={$blockId}")->find();
            if (empty($blockInfo)) {
                ajaxReturn('没有找到该地块信息', 300);
            }
            if (empty($base_id)) {
                ajaxReturn('请选择所属基地', 300);
            }
            if (empty($sn)) {
                ajaxReturn('地块编号不能为空', 300);
            }
            $existSn = $block->where("sn='{$sn}' AND base_id={$base_id} AND id!={$blockId}")->count();
            if ($existSn) {
                ajaxReturn('该地块编号已存在', 300);
            }
            //判断该地块下是否有苗木
            $hasTree = M('Tree')->where("block_id={$blockId}")->count();
            if ($hasTree) {
                if ($sn != $blockInfo['sn']) {
                    ajaxReturn('该地块下有苗木,不能修改地块编号', 300);
                }
            }
            if (empty($area)) {
                ajaxReturn('地块面积不能为空', 300);
            }
            if (floatval($area) < 0) {
                ajaxReturn('地块面积不能小于零', 300);
            }

            $data = $block->create();

            if ($data) {
                $data['upd_time'] = time();
                $ret = $block->where("id={$blockId}")->save($data);

                if ($ret !== false) {
                    ajaxReturn('修改地块成功', 200, '', '', '', 'Admin/Block/blockList');
                } else {
                    ajaxReturn('修改地块失败', 300);
                }
            } else {
                ajaxReturn('创建数据对象失败', 300);
            }
        } else {
            $blockId = I('get.blockId', 0);

            if (empty($blockId)) {
                ajaxReturn('地块ID不能为空', 300);
            }

            $blockInfo = M('Block')->where("id={$blockId}")->find();
            if (empty($blockInfo)) {
                ajaxReturn('没有找到该地块信息', 300);
            }

            //获取所有基地
            $bases = M('Base')->field('id,name')->where('status=1')->select();

            //判断该地块下是否有苗木
            $hasTree = M('Tree')->where("block_id={$blockId}")->count();

            $this->assign('blockInfo', $blockInfo);
            $this->assign('bases', $bases);
            $this->assign('hasTree', $hasTree);
            $this->display();
        }
    }

    /**
     * 删除地块
     */
    public function delBlock() {
        $ids = I('get.ids', '');

        if (empty($ids)) {
            ajaxReturn('请选择删除项', 300);
        }

        $idsArr = explode(',', $ids);
        if (!empty($idsArr)) {
            foreach ($idsArr as $blockId) {
                $hasTree = M('Tree')->where("block_id={$blockId}")->count();
                if ($hasTree) {
                    ajaxReturn("地块ID为{$blockId}的有苗木,不能删除", 300);
                }
            }
        }

        $ret = M('Block')->where("FIND_IN_SET(id,'{$ids}')")->delete();
        if ($ret !== false) {
            ajaxReturn('删除成功', 200, '', '', '', 'Admin/Block/blockList');
        } else {
            ajaxReturn('删除失败', 300);
        }
    }

    /**
     * 删除所有苗木
     */
    public function delAllTree() {
        $ids = I('get.ids', '');

        if (empty($ids)) {
            ajaxReturn('请选择删除项', 300);
        }

        $ret = M('Tree')->where("FIND_IN_SET(block_id,'{$ids}')")->delete();
        if ($ret !== false) {
            ajaxReturn('删除所有苗木成功', 200, '', '', '', 'Admin/Tree/treeList');
        } else {
            ajaxReturn('删除所有苗木失败', 300);
        }
    }

    /**
     * 获取基地下地块
     */
    public function getBaseBlock() {
        $baseId = I('post.baseId', 0);

        if (empty($baseId)) {
            ajaxReturn('', 300, array());
        }

        $list = M('Block')->field('id,sn')->where("status=1 AND base_id={$baseId}")->order('sort ASC')->select();
        if (empty($list)) {
            ajaxReturn('', 300, array());
        }
        ajaxReturn('', 200, array('list' => $list));
    }

    /**
     * 批量设置苗木自有属性
     */
    public function batchSetAttr() {
        if (IS_POST) {
            $base_id = I('post.base_id', 0);
            $block_id = I('post.block_id', 0);
            $large_type = I('post.large_type', 0);
            $small_type = I('post.small_type', 0);
            $attr = I('post.attr', array());

            if (empty($base_id)) {
                ajaxReturn('基地ID不能为空', 300);
            }
            if (empty($block_id)) {
                ajaxReturn('地块ID不能为空', 300);
            }
            if (empty($large_type)) {
                ajaxReturn('请选择苗木分类', 300);
            }
            if (empty($small_type)) {
                ajaxReturn('请选择苗木种类', 300);
            }
            if (!empty($attr)) {
                foreach ($attr as $val) {
                    if (empty($val)) {
                        ajaxReturn('请设置苗木自有属性', 300);
                    }
                }
            }

            $treeAttrTable = C('DB_PREFIX') . 'tree_attr';
            $treeList = M('Tree')->field('t.id')
                    ->alias('t')
                    ->where("block_id={$block_id} AND type_id={$small_type} AND not exists(SELECT ta.id FROM {$treeAttrTable} AS ta WHERE ta.tree_id=t.id)")
                    ->select();

            if (empty($treeList)) {
                ajaxReturn('没有苗木需要设置自有属性', 300);
            }

            $isExec = true;
            M('TreeAttr')->startTrans();
            foreach ($treeList as $tree) {
                $treeId = $tree['id'];
                $insTreeAttr = array();
                foreach ($attr as $key => $attrVal) {
                    if (!empty($attrVal)) {
                        if (is_array($attrVal)) {
                            foreach ($attrVal as $val) {
                                $insTreeAttr[] = array(
                                    'tree_id' => $treeId,
                                    'attr_id' => $key,
                                    'attr_value' => $val,
                                );
                            }
                        } else {
                            $insTreeAttr[] = array(
                                'tree_id' => $treeId,
                                'attr_id' => $key,
                                'attr_value' => $attrVal,
                            );
                        }
                    }
                }
                $ins = M('TreeAttr')->addAll($insTreeAttr);

                if ($ins === false) {
                    $isExec = false;
                }
            }

            if ($isExec) {
                M('TreeAttr')->commit();
                ajaxReturn('批量设置苗木自有属性成功', 200, '', '', '', 'Admin/Tree/treeList');
            } else {
                M('TreeAttr')->rollback();
                ajaxReturn('批量设置苗木自有属性失败', 300);
            }
        } else {
            $blockId = I('get.blockId', 0);
            if (empty($blockId)) {
                ajaxReturn('地块ID不能为空', 300);
            }

            //地块信息
            $blockInfo = M('Block')->field('bl.id,bl.sn,ba.id AS base_id,ba.name AS base_name')
                    ->alias('bl')
                    ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                    ->where("bl.id={$blockId}")
                    ->find();

            //获取该地块下苗木分类信息
            $smallTypeIdArr = M('Tree')->where("block_id={$blockId}")->group('type_id')->getField('type_id', true);
            $smallTypeIds = implode(',', $smallTypeIdArr);

            $largeType = M('TreeType')->field('tt2.id,tt2.name')
                    ->alias('tt')
                    ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                    ->where("FIND_IN_SET(tt.id,'{$smallTypeIds}')")
                    ->select();

            $this->assign('blockInfo', $blockInfo);
            $this->assign('largeType', $largeType);
            $this->display();
        }
    }

}
